package com.hyt.application.service;

import com.alibaba.fastjson.JSON;
import com.hyt.application.api.request.CommonRequest;
import com.hyt.application.api.request.NBCBEBankData;
import com.hyt.application.api.request.OutwardRemittanceQueryRequest;
import com.hyt.application.api.response.CommonRemittanceResponse;
import com.hyt.application.api.response.OutwardRemittanceQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * 速汇盈二代XML格式报文服务实现层
 *
 * @author hytkk
 * 20220813
 */
@Component
@Slf4j
public class OutwardRemittanceServiceV2 {

    /**
     * 接收报文url
     */
    private static final String URL = "http://127.0.0.1:8080/directlink/httpAccess";
    /**
     * 签名ip
     */
    private static final String VERIFY_IP = "127.0.0.1";
    /**
     * 签名端口
     */
    private static final int VERIFY_PORT = 8010;

    /**
     * cookies
     */
    private String cookies = null;
    /**
     * sessionId
     */
    private String sessionId = "-1";

    /**
     * 汇出汇款查询方法实现
     *
     * @param nbcbeBankData
     * @return
     */
    public CommonRemittanceResponse outwardRemittanceQuery(NBCBEBankData nbcbeBankData){
        CommonRemittanceResponse queryResponse = new OutwardRemittanceQueryResponse();
        try{
            nbcbeBankData.setServiceId("outward_remittance_query_v2");
            queryResponse =  executeServerHttpServiceOut(nbcbeBankData);
        }catch (Exception e){
            log.error(e.toString());
        }
        return queryResponse;
    }

    /**
     * 执行交易
     *
     * @param
     * @throws Exception
     */
    public CommonRemittanceResponse executeServerHttpServiceOut(NBCBEBankData request) throws Exception {
        // 处理交易的url
        java.net.URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (cookies != null) {
            // 如果已登录，设置coikie
            connection.setRequestProperty("cokie", cookies);
        }
        // 请求以utf-8格式编码并且已json格式发送报文
        connection.setRequestProperty("content-type", "application/json;charset=utf-8");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        // post方式发送
        connection.setRequestMethod("POST");
        OutputStream out = connection.getOutputStream();
        // 组装完整的交易报文
        String reqData = "aa";
        // utf-8 编码发送
        System.out.println("请求报文：\n" + reqData);
        out.write(reqData.getBytes("UTF-8"));
        out.flush();
        out.close();
        int retCode = connection.getResponseCode();
        if (retCode != 200) {
            throw new Exception("交易出错！retCode=" + retCode);
        }
        // 设置cookie
        Map heads = connection.getHeaderFields();
        Object[] headNames = heads.keySet().toArray();
        for (int i = 0; i < headNames.length; i++) {
            if (headNames[i] == null) {
                continue;
            }
            if ("Set-Cookie".equalsIgnoreCase((String) headNames[i])) {
                this.cookies = connection.getHeaderField(headNames[i]
                        .toString());
            }
        }
        int len = connection.getContentLength();
        byte[] retData = readContent(connection.getInputStream(), len);
        String retStr = new String(retData, "UTF-8");
        System.out.println("【返回报文】Ret Data:\n " + retStr);
        CommonRemittanceResponse response = JSON.parseObject(retStr,OutwardRemittanceQueryResponse.class);
        return response;
        //parseReturnValue(retStr);
    }
    /**
     * 读取返回信息
     *
     * @param in
     * @param len
     * @return
     * @throws IOException
     */
    private byte[] readContent(InputStream in, int len) throws IOException {
        if (len <= 0) {
            byte[] buf = new byte[2048];
            byte[] readBuf = new byte[1024];
            int totalLen = 0;
            while (true) {
                int readLen = in.read(readBuf);
                if (readLen <= 0)
                    break;
                if (totalLen + readLen > buf.length) {
                    byte[] tmp = new byte[buf.length + readLen + 1024];
                    System.arraycopy(buf, 0, tmp, 0, totalLen);
                    buf = tmp;
                }
                System.arraycopy(readBuf, 0, buf, totalLen, readLen);
                totalLen = totalLen + readLen;
            }
            byte[] retBuf = new byte[totalLen];
            System.arraycopy(buf, 0, retBuf, 0, totalLen);
            return retBuf;
        } else {
            int totalLen = 0;
            byte[] buf = new byte[len];
            while (totalLen < len) {
                int readLen = in.read(buf, totalLen, len - totalLen);
                if (readLen <= 0)
                    break;
                totalLen = totalLen + readLen;
            }
            return buf;
        }
    }



}
